document.addEventListener("DOMContentLoaded", function() {
    var connectBtn = document.getElementById("connectBtn");
    var disconnectBtn = document.getElementById("disconnectBtn");
    var messageContainer = document.getElementById("messageContainer");

    var websocket = null;

    connectBtn.addEventListener("click", function() {
        initWebSocket();
    });

    disconnectBtn.addEventListener("click", function() {
        destroyWebSocket();
    });

    function initWebSocket() {
        websocket = new WebSocket("localhost:8081/websocket/1111");

        websocket.onopen = function() {
            websocketOnOpen();
        };

        websocket.onerror = function() {
            websocketOnError();
        };

        websocket.onmessage = function(event) {
            websocketOnMessage(event);
        };

        websocket.onclose = function() {
            websocketOnClose();
        };
    }

    function destroyWebSocket() {
        if (websocket) {
            websocket.close();
        }
    }

    function websocketOnOpen() {
        messageContainer.innerHTML = "WebSocket连接已建立";
    }

    function websocketOnError() {
        messageContainer.innerHTML = "WebSocket连接发生错误";
    }

    function websocketOnMessage(event) {
        var message = event.data;
        messageContainer.innerHTML = "收到消息：" + message;
    }

    function websocketOnClose() {
        messageContainer.innerHTML = "WebSocket连接已关闭";
    }
});
